import cn from 'classnames';
import { FC } from 'react';
import { SubmitHandler } from 'react-hook-form';

import { IAuthForm, useLoginForm } from '../../../hooks/useLoginForm.ts';
import Page from '../../layout/Page';
import UiContainer from '../../layout/UiContainer';

import styles from './AuthPage.module.scss';
import { AuthPageProps } from './AuthPage.props';

const AuthPage: FC<AuthPageProps> = () => {
  const {
    register,
    handleSubmit,
    reset,
    isPending: isLoading,
    mutate,
    error,
  } = useLoginForm();

  const onFormSubmit: SubmitHandler<IAuthForm> = data => {
    mutate(data);
  };

  return (
    <Page>
      <UiContainer
        as={'main'}
        className={cn(styles.authPage)}
      >
        <form
          className={cn(styles.auth)}
          onSubmit={handleSubmit(onFormSubmit)}
        >
          <h1>Авторизация</h1>

          <section className={cn(styles.body)}>
            <article className={cn(styles.inputRow)}>
              <label htmlFor={'login-input'}>Логин</label>
              <input
                type={'text'}
                id={'login-input'}
                {...register('login')}
              />
            </article>

            <article className={cn(styles.inputRow)}>
              <label htmlFor={'password-input'}>Пароль</label>
              <input
                type={'password'}
                id={'password-input'}
                {...register('password')}
              />
            </article>

            <article>
              <button
                className={cn(
                  'px-[.5rem] py-[.25rem] bg-neutral-200 rounded-md',
                )}
                onClick={() => reset()}
                type={'reset'}
              >
                Сбросить
              </button>
            </article>
          </section>

          {(error || undefined) !== undefined && (
            <section className={cn(styles.messageDisplay, styles.error)}>
              ⚠️ Ошибка!
            </section>
          )}

          <button
            type='submit'
            disabled={isLoading}
          >
            {!isLoading ? 'Войти' : '...'}
          </button>
        </form>
      </UiContainer>
    </Page>
  );
};

export default AuthPage;
